package com.example.springsecurity.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springsecurity.domain.AssignExperiment;
import com.example.springsecurity.domain.Notice;
import com.example.springsecurity.domain.RoProject;
import com.example.springsecurity.domain.SysUser;
import com.example.springsecurity.security.SecurityUtils;
import com.example.springsecurity.service.NoticeService;
import com.example.springsecurity.utils.ResultBean;
import com.example.springsecurity.utils.convert.Convert;
import com.example.springsecurity.utils.ifnull.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName NoticeController
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-09-28 15:02
 **/
@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    /**
     * 查看当前登录的人发布的通知
     * @param pageNum
     * @param pageSize
     * @param notice
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:getAll')")
    @GetMapping("/getAllNotice")
    @ResponseBody
    public ResultBean getAllNotice(Integer pageNum,Integer pageSize,Notice notice){
        /**
         * 获取当前登录人id
         */
        notice.setIssueUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
        if(StringUtils.isNull(pageNum) || pageNum == 0){
            pageNum = 1;
        }
        if(StringUtils.isNull(pageSize) || pageSize == 0){
            pageSize = 10;
        }
        try{
            /**
             * 分页
             */
            PageHelper.startPage(pageNum,pageSize);
            //获取内容
            List<Notice> list = noticeService.getAllNotice(notice);
            PageInfo<Notice> pageInfo = new PageInfo<Notice>(list);
            return ResultBean.success("获取内容成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("当前用户没有发布过通知");
        }
    }


    /**
     * 项目管理员发布通知给全部用户
     * @param notice
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:issueAll')")
    @PostMapping("/issueAll")
    @ResponseBody
    public ResultBean issueAll(@RequestBody Notice notice){
        /**
         * 获取当前登录人id
         */
        notice.setIssueUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
        /**
         * 获取所有用户id
         */
        List<Long> userIds = noticeService.getAllUserIds();
        try{
            noticeService.issueNoticeUser(notice,userIds);
            return ResultBean.success("发布通知成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("发布通知失败");
        }
    }


    /**
     * 教师/项目负责人发布通知给指定用户
     * @param data
     * {
     *     "noticeContent":"10",
     *     "noticeIntroduce":"12456",
     *     "validDate":"2020-09-29 10:00:00",
     *     "experimentId":1,
     *     "assignId":1,
     *     "userIds":[1,2,3]
     * }
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:issueStudent')")
    @PostMapping("/issueStudent")
    @ResponseBody
    public ResultBean issueStudent(@RequestBody String data){
        /**
         * 解析信息
         */
        JSONObject jsonObject = JSON.parseObject(data);
        //创建通知对象
        Notice notice = new Notice();
        notice.setNoticeContent(jsonObject.getString("noticeContent"));
        notice.setNoticeIntroduce(jsonObject.getString("noticeIntroduce"));
        notice.setValidDate(jsonObject.getDate("validDate"));
        notice.setExperimentId(jsonObject.getInteger("experimentId"));
        notice.setAssignId(jsonObject.getLong("assignId"));
        /**
         * 设置当前登录用户id
         */
        notice.setIssueUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
        /**
         * 解析用户id
         */
        String data1 = jsonObject.getString("userIds");
        String msg = data1.substring(1,data1.length()-1);
        List<Long> userIds = Arrays.asList(Convert.toLongArray(msg));
        try{
            noticeService.issueNoticeUser(notice,userIds);
            return ResultBean.success("发布通知成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("发布通知失败");
        }
    }


    /**
     * 用户查看所有未读通知
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:getNewNotice')")
    @GetMapping("/getNewNotice")
    @ResponseBody
    public ResultBean getNewNotice(){
        /**
         * 获取当前登录用户id
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        try{
            List<Notice> notices = noticeService.getNoticeNoRead(userId);
            return ResultBean.success("成功获取到内容",notices);
        }catch (Exception e){
            return ResultBean.error("没有获取到内容");
        }
    }


    /**
     * 查看给自己发送的所有通知
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:getAllNoticeToMyself')")
    @GetMapping("/getAllNoticeToMyself")
    @ResponseBody
    public ResultBean getAllNoticeToMyself(Integer pageNum,Integer pageSize){
        if(StringUtils.isNull(pageNum) || pageNum == 0){
            pageNum = 1;
        }
        if(StringUtils.isNull(pageSize) || pageSize == 0){
            pageSize = 10;
        }
        /**
         * 获取当前登录用户id
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        try{
            PageHelper.startPage(pageNum,pageSize);
            //获取内容
            List<Notice> notices = noticeService.getAllNoticeToMyself(userId);
            PageInfo<Notice> pageInfo = new PageInfo<Notice>(notices);
            return ResultBean.success("成功获取到内容",pageInfo);
        }catch (Exception e){
            return ResultBean.error("没有获取到内容");
        }
    }


    /**
     * 此处根据通知id获取通知详情
     *    通知详情包括内容时间有效期等
     *    另外如果是项目负责人或教师发布的通知，则还有实验名称，布置安排名称 以及通知给了谁
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:getAllNoticeToMyself')")
    @GetMapping("/getNoticeByNoticeId")
    @ResponseBody
    public ResultBean getNoticeByNoticeId(Long noticeId){
        return noticeService.getNoticeByNoticeId(noticeId);
    }


    /**
     * 删除通知
     * @param data  {"noticeIds":[1,2,3]}
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:deleteNotice')")
    @PostMapping("/deleteNotice")
    @ResponseBody
    public ResultBean deleteNotice(@RequestBody String data){
        /**
         * 解析通知ids
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String ids = jsonObject.getString("noticeIds");
        String noticeId = ids.substring(1,ids.length()-1);
        /**
         * 获取id集合
         */
        Long[] noticeIds = Convert.toLongArray(",",noticeId);
        try {
            noticeService.deleteNotice(noticeIds);
            return ResultBean.success("删除成功");
        }catch (Exception e){
            return ResultBean.error("删除失败");
        }
    }


    /**
     * 用户查看通知
     * @param data   {"noticeId":}
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:lookNotice')")
    @PostMapping("/lookNotice")
    @ResponseBody
    public ResultBean lookNotice(@RequestBody String data){
        /**
         * 获取当前登录人id
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        /**
         * 解析参数
         */
        Long noticeId = JSONObject.parseObject(data).getLong("noticeId");
        /**
         * 修改已读状态
         */
        try{
            Notice notice = noticeService.lookNotice(noticeId,userId);
            return ResultBean.success("已查看",notice);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error("查看失败");
        }
    }

    /**
     * 获取当前登录人(负责人,教师)负责的实验项目
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('sys:notice:chargeProject')")
    @PostMapping("/getChargeProject")
    @ResponseBody
    public ResultBean getChargeProject(){
        /**
         * 获取当前登录人id
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        /**
         * 根据当前登录人id获取所负责的实验
         */
        try{
            List<RoProject> roProjects = noticeService.getProjects(userId);
            return ResultBean.success("获取数据成功",roProjects);
        }catch (Exception e){
            return ResultBean.error("当前无负责的项目");
        }
    }


    /**
     * 根据项目实验id获取当前登录教师/负责人布置的实验情况
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:getAssignByProjectId')")
    @PostMapping("/getAssignByProjectId")
    @ResponseBody
    public ResultBean getAssignByProjectId(@RequestBody String data){
        /**
         * 获取当前登录用户
         */
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        /**
         * 解析出项目实验id
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer projectId = jsonObject.getInteger("projectId");
        try{
            List<AssignExperiment> assignExperiments = noticeService.getAssignExperiment(projectId,userId);
            return ResultBean.success("成功获取信息",assignExperiments);
        }catch (Exception e){
            return ResultBean.error("获取信息失败");
        }
    }


    /**
     * 根据布置id获取布置给的学生用户
     * @param data
     * @return
     */
    //@PreAuthorize("@ss.hasAnyPermi('sys:notice:getUserByAssignId')")
    @PostMapping("/getUserByAssignId")
    @ResponseBody
    public ResultBean getUserByAssignId(@RequestBody String data){
        /**
         * 解析出布置id
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        Long assignId = jsonObject.getLong("assignId");
        try{
            List<SysUser> sysUsers = noticeService.getSysUserByAssignId(assignId);
            return ResultBean.success("获取用户成功",sysUsers);
        }catch (Exception e){
            return ResultBean.error("获取用户失败");
        }
    }
}
